<!--登陆页面的背景图-->
<template>
  <div class="banner">
    <div class="bg">
      <div class="logink">
        <div class="logink_k">
          <p>
            <span
              v-for="(item,index) in nav"
              :key="item.id"
              :class=" item.id == active ? 'active' : '' "
              @click="changes($event,index)"
            >{{ item.name }}</span>
          </p>
          <div class="content">
            <!-- 账户登录 -->
            <div v-show="account">
              <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
                <el-form-item prop="name">
                  <el-input
                    v-model="ruleForm.name"
                    type="text"
                    placeholder="请输入用户名/邮箱/手机号"
                    prefix-icon="el-icon-info"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="passWord">
                  <el-input
                    v-model="ruleForm.passWord"
                    type="password"
                    placeholder="请输入密码"
                    prefix-icon="el-icon-edit"
                  ></el-input>
                </el-form-item>
              </el-form>
              <!-- 滑块验证 -->
              <Verify
                style="margin-top:18px;"
                @success="success"
                @error="error"
                :type="3"
                :barSize="barSize"
                :showButton="false"
              ></Verify>

              <ol>
                <li>
                  <el-checkbox v-model="checked">自动登录</el-checkbox>
                </li>
                <router-link to="/forgetPassword" tag="li">忘记密码 ?</router-link>
                <!-- <li >忘记密码 ?</li> -->
              </ol>
              <el-button
                class="Verification"
                type="primary"
                @click="submitForm(ruleForm)"
                :loading="loading"
              >登录</el-button>
            </div>

            <!-- 短信验证码登录 -->
            <div v-show="!account">
              <el-form :model="ruleForm1" :rules="rules1" ref="ruleForm1" class="demo-ruleForm">
                <el-form-item prop="tel">
                  <el-input
                    v-model="ruleForm1.tel"
                    type="text"
                    placeholder="请输入手机号"
                    prefix-icon="el-icon-phone"
                  ></el-input>
                </el-form-item>
                <!-- 发送短信验证码按钮 -->
                <el-button class="Verification" @click="codeinfor" :disabled="disabling">
                  {{ codetexts }}
                  <span v-show="showS">s</span>
                </el-button>

                <el-form-item prop="code">
                  <el-input
                    v-model="ruleForm1.code"
                    type="text"
                    placeholder="短信验证码"
                    prefix-icon="el-icon-message"
                  ></el-input>
                </el-form-item>
              </el-form>

              <ol v-show="account">
                <li>
                  <el-checkbox v-model="checked">自动登录</el-checkbox>
                </li>
                <li>忘记密码 ?</li>
              </ol>
              <el-button
                class="Verification"
                type="primary"
                @click="codeLogin(ruleForm1)"
                :loading="loading"
              >登录</el-button>
            </div>
          </div>
          <div class="btn" @click="jumpRegiter">免费注册 有惊喜 ></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Verify from 'vue2-verify'
export default {
  name: "loginBanner",

  data() {
    return {
      Verification: false,
      barSize: {
        width: '100%', height: '40px'
      },
      // disabled1: true,
      loading: false, // 登录的loading的小样
      disabling: false, //发送验证码按钮是否能够点击
      showS: 0, // s 时候显示
      btn: "点击按钮进行验证", //
      codetexts: "发送短信验证码", //

      ruleForm: {
        name: "",
        passWord: ""
      },

      ruleForm1: {
        tel: "",
        code: ""
      },

      rules: {
        name: [
          {
            required: true,
            // min: 6,
            // max: 12,
            message: "请输入正确的用户名/邮箱/手机号",
            trigger: "blur"
          }
        ],
        passWord: [
          {
            required: true,
            // min: 6,
            // max: 16,
            message: "密码不能为空",
            trigger: "blur"
          }
        ]
      },
      rules1: {
        tel: [
          {
            required: true,
            // min: 6,
            // max: 16,
            message: "电话号码不能为空",
            trigger: "blur"
          }
        ],
        code: [
          {
            required: true,
            // min: 6,
            // max: 16,
            message: "验证码不能为空",
            trigger: "blur"
          }
        ]
      },

      account: true, //  登录的显示与隐藏
      checked: false, //  自动登录的状态
      active: 0,

      nav: [
        {
          name: "用户登录",
          id: 0
        },
        {
          name: "短信登录",
          id: 1
        }
      ]
    }
  },

  components: {
    Verify
  },

  methods: {
    // 验证成功后的回调函数
    success() {
      this.Verification = true
    },
    // 验证失败后的回调函数
    error() {
      this.Verification = false
    },

    // 跳转到注册页面
    jumpRegiter() {
      this.$router.push({
        name: "register"
      })
    },

    checking() {
      console.log("点击了验证按钮")
    },

    changes(ev, index) {
      this.active = index
      this.account = !index
    },

    // 短信验证码
    codeinfor() {
      let phone = parseInt(this.ruleForm1.tel)
      // console.log(phone)
      this.$http({
        method: "post",
        url: `/api/index/common/sendMsg`,
        headers: { "X-Requested-With": "XMLHttpRequest" }, // 必须加这个请求头 否则报错：500
        data: {
          phone,
          code: `SMS_143540007`
        }
      })
        .then(res => {
          let _data = res.data
          // console.log(_data)
        })
        .catch(err => {
          console.log("出错了请检查代码")
        })

      this.codetexts = 60 // 60秒
      this.showS = true // s 显示出来
      this.disabling = true // 按钮不能够点击
      let timer = setInterval(() => {
        this.codetexts = this.codetexts - 1
        if (this.codetexts == 0) {
          clearInterval(timer)
          this.codetexts = "请重新发送短信验证码"
          this.showS = false
          this.disabling = false
        }
      }, 1000)
    },
    // 短信登录
    codeLogin(formName) {
      this.loading = true
      let phone = formName.tel,
        smscode = formName.code,
        code = "phone",
        params = {
          code, // 后添加的状态码
          phone,
          smscode,
          jwt: "" // 为空 先不传递
        }
      this.$http({
        method: "post",
        url: `/api/index/login/login`,
        data: params
      })
        .then(res => {
          // console.log(res)
          const _data = res.data
          // console.log(_data)

          this.$store.commit("UserInfor", _data) // 保存用户信息
          console.log(_data.State.Code)
          if (_data.State.Code == 200) {
            // console.log(this.$store.state.token)                    // token成功

            params.jwt = _data.jwt.access_token
            console.log(params)
            try {
              this.$http({
                method: "post",
                url: `/api/index/login/login`,
                data: params
              })
                .then(response => {
                  // 登录成功后的处理
                  // console.log(response)
                  if (response.data.State.Code == 200) {
                    this.$store.commit("set_token", _data.jwt.access_token)
                    // vuex 创建 set_token方法 参数：_data.jwt.access_token
                    this.loading = false
                    this.$notify({
                      title: "登录成功",
                      message: "可以购买您所需要的商品了...",
                      type: "success"
                    })
       
                    if(this.$route.query.redirect){
                      this.$router.push(this.$route.query.redirect);
                    }else{
                      this.$router.push('/');
                    }
        
                  } else if (response.data.State.Code == 800) {
                    this.$notify.error({
                      title: "验证码错误...",
                      message: "请核对验证码..."
                    })
                  }
                })
                .catch(err => {
                  console.log(err)
                })
            } catch (error) {
              console.log("短信登录接口出现问题...")
            }
          } else if (_data.State.Code == 800) {
            this.$store.commit("del_token")
            this.loading = false
            this.$notify.error({
              title: "验证码错误",
              message: "请输入正确的验证码..."
            })
            this.$router.push("/login")
          } else if (_data.State.Code == 1600) {
            this.$store.commit("del_token")
            this.loading = false
            this.$notify.error({
              title: "验证码过期",
              message: "请重新发送验证码..."
            })
            this.$router.push("/login")
          } else if (_data.State.Code == 1000) {
            this.$store.commit("del_token")
            this.loading = false
            this.$notify.error({
              title: "该手机号码未进行注册 ",
              message: "请注册后再登录..."
            })
            console.log(_data.State.Message)
            this.$router.push("/login")
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 账户登录
    submitForm(formName) {
      console.log(
        this.ruleForm.name,
        this.ruleForm
      )
      if (this.ruleForm.name && this.ruleForm.passWord) {
        if (this.Verification) {  // 滑块验证
          this.loading = true
          let username = formName.name,
            password = formName.passWord,
            code = "account",
            params = {
              code, // 后添加的状态码
              username,
              password,
              jwt: ""
            }
          // console.log(params)
          // let that = this

          this.$http({
            method: "post",
            url: `/api/index/login/login`,
            data: params
          })
            .then(res => {
              console.log(res)
              const _data = res.data
              this.$store.commit("UserInfor", _data) // 保存用户信息
              let _code = _data.State.Code
              console.log(_code)
              if (_code == 200) {
                this.loading = false
                // console.log(this.$store.state.token)                    // token成功
                params.jwt = _data.jwt.access_token
                // console.log(params.jwt)
                this.$http({
                  method: "post",
                  url: `/api/index/login/login`,
                  data: params
                })
                  .then(response => {
                    // 登陆成功后的处理
                    if (response.data.State.Code == 200) {

                      // 自动登录开始
                      if(this.checked){
                        const NamePassword = {
                          name: this.ruleForm.name,
                          passWord: this.ruleForm.passWord
                        }
                        localStorage.setItem('NamePassword',JSON.stringify(NamePassword))
                        localStorage.setItem('lastChecked',JSON.stringify(this.checked))
                      } else{
                        localStorage.removeItem('NamePassword')
                        localStorage.removeItem('lastChecked')
                      }
                      
                      // 自动登录结束

                      this.$store.commit("set_token", _data.jwt.access_token)
                      // vuex 创建 set_token方法 参数：_data.jwt.access_token
                      this.loading = false
                      this.$notify({
                        title: "登录成功",
                        type: "success"
                      })
                      
                      if(this.$route.query.redirect){
                        this.$router.push(this.$route.query.redirect);
                      }else{
                        this.$router.push('/');
                      }
                      
                    }
                  })
                  .catch(err => {
                    console.log(err)
                  })
              } else if (_code == 2000) {
                // 用户名和密码错误
                this.$store.commit("del_token")
                this.$notify.error({
                  title: "登录失败",
                  message: "用户名或密码错误 请重新输入..."
                })
                console.log(_data.State.Message)
                this.loading = false
                this.ruleForm.name = ''
                this.ruleForm.passWord = ''
              } else if (_code == 800) {
                this.$notify.error({
                  title: "验证码错误...",
                  message: "请重新输入验证码..."
                })
              } else if (_code == 1000) {
                this.$notify.error({
                  title: "手机号未注册...",
                  message: "请重新正确的账号..."
                })
              }
            })
            .catch(err => {
              console.log(err)
            })

        } else {
          this.$notify({
            title: "请把滑块推到最右侧完成验证...",
            // message: '这是一条警告的提示消息',
            type: "warning"
          })
        }
      } else {
        this.$notify.error({
          title: '错误',
          message: '用户名或密码不能为空...'
        })
      }

    },

    // 初始化 登录的页面显示情况
    loginInit() {
      const isAutoLogin = localStorage.getItem('NamePassword')
      const lastChecked = localStorage.getItem('lastChecked')
      if(lastChecked === 'true'){
        console.log('上一次自动登录已经勾选')
        this.checked = true
        this.ruleForm.name= JSON.parse(isAutoLogin).name
        this.ruleForm.passWord=JSON.parse(isAutoLogin).passWord
      } 
    }
  },

  mounted() {
    this.loginInit()
  }
}
</script>
<style lang="scss" scoped>
.banner {
  width: 100%;
  height: 522px;
  background: url("../../../assets/images/2019pis01.jpg") 50% 0px no-repeat;
  .bg {
    width: 1200px;
    height: 522px;
    margin: auto;

    .logink {
      width: 364px;
      height: 442px;
      background: #ffffff;
      float: right;
      margin-top: 40px;
      .logink_k {
        width: 339px;
        margin: auto;
        p {
          width: 100%;
          padding-top: 10px;
          border-bottom: 1px solid #e6e6e6;
          display: flex;
          flex-direction: row;
          justify-content: space-around;
          span {
            display: inline-block;
            width: 100px;
            text-align: center;
            font-size: 16px;
            font-weight: 800;
            padding-bottom: 3px;
            line-height: 32px;
            // &:last-child{
            //     border-left: 1px solid #e6e6e6;
            // }
            cursor: pointer;
            user-select: none; // 禁止用户选择文字
          }
          .active {
            border-bottom: 2px solid #409eff;
            color: #409eff;
          }
        }
        .content {
          width: 339px;
          // height: 306px;
          margin: auto;
          // background: #49e21a;
          div {
            width: 310px;
            margin: auto;
            // background: #23c539;
            text-align: center;
            .el-input {
              margin-top: 38px;
            }
            .Verification {
              width: 100%;
              margin-top: 20px;
              letter-spacing: 1px;
            }
            ol {
              display: flex;
              flex-direction: row;
              justify-content: space-between;
              margin-top: 20px;
              li:last-child {
                cursor: pointer;
                &:hover {
                  color: #409eff;
                }
              }
            }
            /deep/ .verify-bar-area {
              .verify-msg {
                position: relative;
              }

            }
          }
        }
        .btn {
          width: 339px;
          // margin: auto;
          margin: 25px auto;
          line-height: 22px;
          cursor: pointer;
          font-size: 14px;
          text-indent: 14px;
          &:hover {
            color: #409eff;
          }
        }
      }
    }
  }
}
</style>
